因為是看筆記教到Kahn's Algorithm,直接練習題,所以沒什麼思路不思路,直接按照算法實作。
#include <iostream>
#include <queue>
#define N 101
using namespace std;
int main(){
int n, m, u, v;
bool adj[N][N];
int ref[N];
while(cin >> n >> m) {
if (n==0 && m==0) break;
// 初始化
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
adj[i][j] = false;
for (int i = 1; i <= n; i++) ref[i] = 0;
// 輸入
for (int i = 1; i <= m; i++) {
cin >> u >> v;
adj[u][v] = true;
}
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
if (adj[i][j]) ref[j]++;
// Kahn's Algorithm
deque<int> Q;
for (int i = 1; i <= n; i++)
if(!ref[i]) Q.push_back(i);
for (int i = 1; i <= n; i++) {
if (Q.empty()) break;
int s = Q.front(); Q.pop_front();
ref[s] = -1;
cout << s << " ";
for (int j = 1; j <= n; j++) {
bool flag = false;
if(adj[s][j]) {
ref[j]--;
flag = true;
}
if(!ref[j] && flag) Q.push_back(j);
}
}
cout << endl;
}
}
雖然說可以輸出任意合理工作順序,但實際上還是得看測資推合理的output
參考:
https://web.ntnu.edu.tw/~algo/DirectedAcyclicGraph.html